package de.rwth.dbis.ugnm.resource;

import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;

import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import com.sun.jersey.core.util.Base64;

import de.rwth.dbis.ugnm.entity.User;
import de.rwth.dbis.ugnm.service.UserService;

@Path("/users/{login}")
@Component
@Scope("request")
public class UserResource {

	@Autowired
	UserService userService;

	@GET
	@Produces("text/xml")
	public User getUser(@PathParam("login") String login, @HeaderParam("authorization") String auth) {
		
		User u = userService.getByLogin(login);
		
		if(null != u){
			if(!authenticated(auth, u)){
				u.setPass(null);
			}
			return u;
		}
		else throw new WebApplicationException(404);
	}
	
	@PUT
    @Consumes("application/json")
    public Response updateUser(@HeaderParam("authorization") String auth, @PathParam("login") String login, JSONObject o) throws JSONException {
        
		if(o == null){
			throw new WebApplicationException(400);
		}
		
		User u = userService.getByLogin(login);
		
		if(u == null){
			throw new WebApplicationException(404);
		}
		
		if(!authenticated(auth, u)){
			throw new WebApplicationException(401);
		}
		
        if (o.has("name")){
        	u.setName(o.getString("name"));
        }
        if (o.has("pass")){
        	u.setPass(o.getString("pass"));
        }
        
        userService.update(u);
		return Response.ok().build();
    }
	
	@DELETE
	public Response deleteUser(@HeaderParam("authorization") String auth, @PathParam("login") String login){
		User u = userService.getByLogin(login);
		
		if(u == null){
			throw new WebApplicationException(404);
		}
		
		if(!authenticated(auth, u)){
			throw new WebApplicationException(401);
		}
		
		userService.delete(u);
		
		return Response.ok().build();
	}

	private boolean authenticated(String authHeader,User u){
		if(authHeader != null){
			String[] dauth = null;
			String authkey = authHeader.split(" ")[1];
			System.out.println("Auth Header: " + authHeader);
			if(Base64.isBase64(authkey)){
				dauth = (new String(Base64.decode(authkey))).split(":");
				System.out.println("Login: " + dauth[0] + "/" + u.getLogin() + " Pass: " + dauth[1] + "/" + u.getPass());
				if(dauth[0].equals(u.getLogin()) && dauth[1].equals(u.getPass())){
					return true;
				}
			}
		}
		return false;
	}

}